package 并发编程17;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author idea
 * @data 2019/2/17
 */
public class Provider implements Runnable {

    //阻塞队列
    private BlockingQueue<String> blockingQueue;

    private static AtomicInteger count = new AtomicInteger();

    public Provider(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        String data = null;
        System.out.println(Thread.currentThread().getName() + " 启动生产者线程！");
        try {
            while (true) {
                try {
                    Thread.sleep(1000);
                    data = "" + count.incrementAndGet();
                    System.out.println("生产了相应的数据：" + data.toString() + " 已经放入队列中了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                //如果满了的话，就不会再加入元素
                if (!blockingQueue.offer(data, 2, TimeUnit.SECONDS)) {
                    System.out.println(Thread.currentThread().getName() + " 放入队列失败了！");
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.out.println(Thread.currentThread().getName() + " 退出生产者模式！");
        }
    }

    public static void main(String[] args) {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
        Thread thread = new Thread(new Provider(queue));
        thread.start();

    }


}
